package com.example.demo.login.security.jwt;

import java.io.IOException;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import com.example.demo.login.security.services.UserDetailsServiceImpl;

public class AuthTokenFilter extends OncePerRequestFilter {
  @Autowired
  private JwtUtils jwtUtils;

  @Autowired
  private UserDetailsServiceImpl userDetailsService;

  private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {
    try {
      logger.debug("AuthTokenFilter processing request: {}", request.getRequestURI());
      String jwt = parseJwt(request);
      logger.debug("Extracted JWT from cookies: {}", jwt != null ? "[REDACTED]" : "null");
      
      if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
        logger.debug("JWT token is valid");
        String username = jwtUtils.getUserNameFromJwtToken(jwt);
        logger.debug("Extracted username from JWT: {}", username);

        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        logger.debug("Loaded user details: {}", userDetails.getUsername());
        
        UsernamePasswordAuthenticationToken authentication = 
            new UsernamePasswordAuthenticationToken(userDetails,
                                                    null,
                                                    userDetails.getAuthorities());
        
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        logger.debug("Setting authentication in SecurityContext: {}", username);
        SecurityContextHolder.getContext().setAuthentication(authentication);
      } else if (jwt == null) {
        logger.debug("No JWT token found in cookies");
      } else {
        logger.debug("JWT token validation failed");
      }
    } catch (Exception e) {
      logger.error("Cannot set user authentication: {}", e.getMessage(), e);
    }

    filterChain.doFilter(request, response);
  }

  private String parseJwt(HttpServletRequest request) {
    String jwt = jwtUtils.getJwtFromCookies(request);
    return jwt;
  }
}
